package jmars.mobile.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import jmars.mobile.common.Investigator;
import jmars.mobile.datainvestigation.Summary;

/**
 * instruction
 * group=1,2
 * target=0
 * 
 * @author Jan
 *
 */
public class MaxMinAvgInterval implements Investigator {

	@Override
	public Long compute(File[] files, FileWriter writer) throws IOException, ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(Summary.dateFormat);
		
		Long total = 0L;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		Long interval;
		Long min=null,max=null,avg=0L,count=0L;
		Map<String,Map<Long,String>> seq=new HashMap<String,Map<Long,String>>();
		Date begin;
		String groupKey,targetKey;
		ArrayList<Entry<Long,String>> l;
		Long ltime = null;
		String lGroup = null;
		boolean groupFlag=(Summary.groupColumns!=null&&!"".equals(Summary.groupColumns));
		for(File inputFile:files){
			seq=new HashMap<String,Map<Long,String>>();
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			while((row=reader.readLine())!=null){
				cols=row.split(Summary.columnSeperator);
				if(Summary.filterRow(cols,true,true)) continue;
				
				groupKey="";
				if(groupFlag)
					for(Integer idx:Summary.groupColumnIdx)
						if(idx<cols.length)
							groupKey=groupKey+"$_$"+cols[idx]+"$_$";
						else groupKey=groupKey+"$_$$_$";
				targetKey="";
				for(Integer idx:Summary.targetColumnIdx)
					if(idx<cols.length&&idx!=null)
						targetKey=targetKey+"$_$"+cols[idx]+"$_$";
					else targetKey=targetKey+"$_$$_$";
				begin=sdf.parse(cols[5]);
				if(!seq.containsKey(targetKey))
					seq.put(targetKey, new HashMap<Long,String>());
				seq.get(targetKey).put(begin.getTime(), groupKey);
				
				total++;
			}
			for(String tk:seq.keySet()){
				l = new ArrayList<Entry<Long,String>>(seq.get(tk).entrySet());    

		        Collections.sort(l, new Comparator<Map.Entry<Long,String>>() {
		            public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
		                return o2.getKey()==o1.getKey()?0:(o2.getKey()<o1.getKey()?1:-1);
		            }
		        });
		        ltime=null;
				for(Entry<Long,String> t:l){
					if(ltime!=null&&!t.getValue().equals(lGroup)){
						interval=t.getKey()-ltime;
						min=(min==null)?interval:(interval<min?interval:min);
						max=(max==null)?interval:(interval>max?interval:max);
						avg=(avg*count+interval)/(++count);
					}
					ltime=t.getKey();
					lGroup=t.getValue();
				}
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		writer.write("%*****************details******************\r\n");
		writer.write("%");
		writer.write("min,max,avg,count\r\n");
		writer.write(min+","+max+","+avg+","+count);
		return total;
	}

}
